<?php
/**
 * NOTICE OF LICENSE
 * This source file is subject to the WDCA SWEET TOOTH (TM) POINTS AND REWARDS 
 * License.
 * The Sweet Tooth License is available at this URL: http://www.wdca.ca/sweet_tooth/sweet_tooth_license.txt
 * 
 * DISCLAIMER
 * By adding to, editing, or in any way modifying this code, WDCA is 
 * not held liable for any inconsistencies or abnormalities in the 
 * behaviour of this code. 
 * By adding to, editing, or in any way modifying this code, the Licensee
 * terminates any agreement of support offered by WDCA, outlined in the 
 * provided Sweet Tooth License. 
 * Upon discovery of modified code in the process of support, the Licensee 
 * is still held accountable for any and all billable time WDCA spent 
 * during the support process.
 * WDCA does not guarantee compatibility with any other framework extension. 
 * WDCA is not responsbile for any inconsistencies or abnormalities in the
 * behaviour of this code if caused by other framework extension.
 * If you did not receive a copy of the license, please send an email to 
 * contact@wdca.ca or call 1-888-699-WDCA(9322), so we can send you a copy 
 * immediately.
 * 
 * @category    Cellphonezone
 * @package     Cellphonezone_Repay
 * @copyright   Copyright (c) 2011 Cellphonezone
 * @Author $Id: config.xml 11 2011-06-22 09:19:46Z gold $
 */
class Cellphonezone_Repay_Model_Sales_Invoice_Total extends Mage_Sales_Model_Order_Invoice_Total_Abstract {
	/**
	 * Collect WesternUnionPayment total for invoice
	 *
	 * @param Mage_Sales_Model_Order_Invoice $invoice
	 * @return Atwix_WesternUnionPayment_Model_Sales_Invoice_Total
	 */
	public function collect(Mage_Sales_Model_Order_Invoice $invoice) {
		$invoice->setPaymentAmount(0);
        $orderPaymentAmount        = $invoice->getOrder()->getPaymentAmount();
        $orderBasePaymentAmount        = $invoice->getOrder()->getBasePaymentAmount();
        if ($orderPaymentAmount) {
            /**
             * Check payment amount in previus invoices
             */
            foreach ($invoice->getOrder()->getInvoiceCollection() as $previusInvoice) {
                if ($previusInvoice->getPaymentAmount() && !$previusInvoice->isCanceled()) {
                    return $this;
                }
            }
            
            $invoice->setPaymentAmount($orderPaymentAmount);
            $invoice->setBasePaymentAmount($orderBasePaymentAmount);

            $invoice->setGrandTotal($invoice->getGrandTotal()+$orderPaymentAmount);
            $invoice->setBaseGrandTotal($invoice->getBaseGrandTotal()+$orderBasePaymentAmount);
        }
        return $this;
	}	
}
